package com.yuzhi.master.drainAlarmRule.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.exception.base.BaseException;
import com.yuzhi.master.drainAlarmRule.domain.DrainAlarmCondition;
import com.yuzhi.master.drainAlarmRule.domain.DrainAlarmRule;
import com.yuzhi.master.drainAlarmRule.domain.OperatorEnum;
import com.yuzhi.master.drainAlarmRule.domain.bo.DrainAlarmConditionBo;
import com.yuzhi.master.drainAlarmRule.domain.bo.DrainAlarmRuleBo;
import com.yuzhi.master.drainAlarmRule.domain.request.DrainAlarmRuleReq;
import com.yuzhi.master.drainAlarmRule.domain.vo.DrainAlarmConditionVo;
import com.yuzhi.master.drainAlarmRule.domain.vo.DrainAlarmRuleVo;
import com.yuzhi.master.drainAlarmRule.mapper.DrainAlarmConditionMapper;
import com.yuzhi.master.drainAlarmRule.mapper.DrainAlarmRuleMapper;
import com.yuzhi.master.drainAlarmRule.service.IDrainAlarmRuleService;
import com.yuzhi.master.drainEvents.domain.vo.DataDictionary;
import com.yuzhi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.yuzhi.common.helper.LoginHelper.getUsername;

@Slf4j
@RequiredArgsConstructor
@Service
public class DrainAlarmRuleServiceImpl extends ServiceImpl<DrainAlarmRuleMapper, DrainAlarmRule> implements IDrainAlarmRuleService {

    private final DrainAlarmRuleMapper drainAlarmRuleMapper;

    private final DrainAlarmConditionMapper drainAlarmConditionMapper;

    private static final AtomicInteger sortCounter = new AtomicInteger(0);

    /* 用户服务类 */
    private final ISysUserService userService;



    private Wrapper<DrainAlarmRule> buildQueryWrapper(DrainAlarmRuleReq request) {
        QueryWrapper<DrainAlarmRule> wrapper = Wrappers.query();
        wrapper.eq("dar.deleted", 0);
        wrapper.eq(StringUtils.isNotBlank(request.getAlarmType()), "dar.alarm_type", request.getAlarmType());
        wrapper.eq(StringUtils.isNotBlank(request.getFacilityType()), "dar.facility_type", request.getFacilityType());
        wrapper.eq(StringUtils.isNotBlank(request.getDeviceIds()), "dar.device_ids", request.getDeviceIds());
        // 处理人员ID查询（多个ID用逗号分隔）
        if (StringUtils.isNotBlank(request.getReceiverIds())) {
            // 分割并过滤有效的ID
            List<String> validIds = Arrays.stream(request.getReceiverIds().split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotEmpty)
                    .collect(Collectors.toList());

            if (!validIds.isEmpty()) {
                // 构建精确匹配条件：ID要么在开头、中间或结尾
                wrapper.and(w -> {
                    for (String id : validIds) {
                        // 匹配三种情况：
                        // 1. 以目标ID开头，后面跟逗号或结束（如"id1,"或"id1"）
                        // 2. 目标ID在中间，前后都有逗号（如",id1,"）
                        // 3. 目标ID在结尾，前面有逗号（如",id1"）
                        w.or()
                                .likeRight("dar.receiver_ids", id + ",")
                                .or()
                                .likeLeft("dar.receiver_ids", "," + id)
                                .or()
                                .eq("dar.receiver_ids", id);
                    }
                });
            }
        }
        return wrapper;
    }

    
    private Wrapper<DrainAlarmRule> selectBuildQueryWrapper(DrainAlarmRuleReq request) {
        QueryWrapper<DrainAlarmRule> wrapper = Wrappers.query();
        wrapper.eq("dar.deleted", 0);
        wrapper.eq(StringUtils.isNotBlank(request.getAlarmType()), "dar.alarm_type", request.getAlarmType());
        // 支持多类型查询：优先使用 facilityTypes，其次解析逗号分隔的 facilityType
        wrapper.in(CollectionUtils.isNotEmpty(request.getFacilityTypes()),"dar.facility_type", request.getFacilityTypes());
        wrapper.eq(StringUtils.isNotBlank(request.getDeviceIds()), "dar.device_ids", request.getDeviceIds());
        // 处理人员ID查询（多个ID用逗号分隔）
        if (StringUtils.isNotBlank(request.getReceiverIds())) {
            // 分割并过滤有效的ID
            List<String> validIds = Arrays.stream(request.getReceiverIds().split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotEmpty)
                    .collect(Collectors.toList());

            if (!validIds.isEmpty()) {
                // 构建精确匹配条件：ID要么在开头、中间或结尾
                wrapper.and(w -> {
                    for (String id : validIds) {
                        // 匹配三种情况：
                        // 1. 以目标ID开头，后面跟逗号或结束（如"id1,"或"id1"）
                        // 2. 目标ID在中间，前后都有逗号（如",id1,")
                        // 3. 目标ID在结尾，前面有逗号（如",id1"）
                        w.or()
                                .likeRight("dar.receiver_ids", id + ",")
                                .or()
                                .likeLeft("dar.receiver_ids", "," + id)
                                .or()
                                .eq("dar.receiver_ids", id);
                    }
                });
            }
        }
        return wrapper;
    }


    /**
     * 实际处理条件转换和字典映射的核心方法
     */
    private void processConditions(DrainAlarmRuleVo ruleVo, Map<String, String> dictMap) {
        if (ruleVo == null || dictMap == null || dictMap.isEmpty()) {
            return;
        }

        // 获取原始条件列表
        List<?> originalConditions = ruleVo.getConditions();
        if (originalConditions == null || originalConditions.isEmpty()) {
            return;
        }

        // 转换类型并处理字典映射
        List<DrainAlarmConditionBo> convertedConditions = originalConditions.stream()
                .map(cond -> convertAndMapCondition(cond, dictMap))
                .filter(Objects::nonNull) // 过滤转换失败的项
                .collect(Collectors.toList());

        // 替换为转换后的列表
        ruleVo.setConditions(convertedConditions);
    }

    /**
     * 转换单个条件并处理字典映射
     */
    private DrainAlarmConditionBo convertAndMapCondition(Object condition, Map<String, String> dictMap) {
        try {
            // 类型转换：DrainAlarmCondition -> DrainAlarmConditionBo
            DrainAlarmCondition originalCondition = (DrainAlarmCondition) condition;
            DrainAlarmConditionBo bo = new DrainAlarmConditionBo();
            BeanUtils.copyProperties(originalCondition, bo);

            // 处理字典映射
            String monitorItemName = bo.getMonitorItemName();
            String mappedName = dictMap.getOrDefault(monitorItemName, monitorItemName);
            bo.setMonitorItemName(mappedName);

            return bo;
        } catch (ClassCastException e) {
            // 处理类型转换异常
            log.error("转换条件类型失败，预期类型: DrainAlarmCondition, 实际类型: {}",
                    condition.getClass().getName(), e);
            return null;
        } catch (Exception e) {
            log.error("处理条件映射时发生异常", e);
            return null;
        }
    }

    /**
     * 统一字段映射处理（用户ID映射、设备ID映射）
     */
    private void handleFieldMapping(List<DrainAlarmRuleVo> records) {
        if (records == null || records.isEmpty()) {
            return;
        }

        // 设备ID映射表
        List<Map<String, String>> viewMappings = drainAlarmRuleMapper.queryOriginalIdAndNameFromView();
        Map<String, String> originalId2NameMap = viewMappings.stream()
                .collect(Collectors.toMap(
                        m -> m.get("original_id"),
                        m -> m.get("name"),
                        (oldVal, newVal) -> newVal
                ));

        // 所有用户ID集合
        List<String> allUserIds = records.stream()
                .map(DrainAlarmRuleVo::getReceiverIds)
                .filter(Objects::nonNull)
                .flatMap(ids -> Arrays.stream(ids.split(",")))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .distinct()
                .toList();

        Map<String, String> regionNameMap = userService.selectUserName(allUserIds);

        // 遍历记录进行映射
        for (DrainAlarmRuleVo item : records) {
            // 用户ID映射
            if (item.getReceiverIds() != null && !item.getReceiverIds().trim().isEmpty()) {
                String userNames = Arrays.stream(item.getReceiverIds().split(","))
                        .map(String::trim)
                        .map(id -> regionNameMap.getOrDefault(id, "未知姓名"))
                        .collect(Collectors.joining(","));
                item.setReceiverIds(userNames);
            }

            // 设备ID映射
            if (item.getDeviceIds() != null && !item.getDeviceIds().trim().isEmpty()) {
                List<String> mappedNames = Arrays.stream(item.getDeviceIds().split(","))
                        .map(String::trim)
                        .map(id -> originalId2NameMap.getOrDefault(id, id))
                        .toList();
                item.setDeviceName(String.join(",", mappedNames));
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(DrainAlarmRuleBo bo) {
        // 1. 如果是“全部设备”，先软删同类型未删除的规则
        if ("0".equals(bo.getDeviceIds())) {
            LambdaQueryWrapper<DrainAlarmRule> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(DrainAlarmRule::getAlarmType, bo.getAlarmType())
                    .eq(DrainAlarmRule::getFacilityType, bo.getFacilityType())
                    .eq(DrainAlarmRule::getDeviceIds, "0")
                    .eq(DrainAlarmRule::getDeleted, 0);
            // 软删除：更新 deleted = 1
            drainAlarmRuleMapper.delete(updateWrapper);
        }

        // 2. 如果是多个设备（用逗号分隔），则每台设备插入一条规则
        if (bo.getDeviceIds().contains(",")) {
            String[] deviceIds = bo.getDeviceIds().split(",");
            for (String deviceId : deviceIds) {
                DrainAlarmRule add = new DrainAlarmRule();
                add.setAlarmType(bo.getAlarmType());
                add.setFacilityType(bo.getFacilityType());
                add.setDeviceIds(deviceId.trim());
                add.setReceiverIds(bo.getReceiverIds());
                add.setIntervalValue(bo.getIntervalValue());
                add.setIntervalUnit(bo.getIntervalUnit());
                add.setRuleType(bo.getRuleType());
                add.setRuleStatus(false);
                add.setTransferWork(bo.getTransferWork());
                add.setHandlerPerson(bo.getHandlerPerson());
                add.setSendMessage(bo.getSendMessage());
                baseMapper.insert(add);
            }
            // 批量插入成功
            return true;
        }

        // 3. 单设备或“全部设备”情况：插入一条
        DrainAlarmRule add = new DrainAlarmRule();
        add.setAlarmType(bo.getAlarmType());
        add.setFacilityType(bo.getFacilityType());
        add.setDeviceIds(bo.getDeviceIds());
        add.setReceiverIds(bo.getReceiverIds());
        add.setIntervalValue(bo.getIntervalValue());
        add.setIntervalUnit(bo.getIntervalUnit());
        add.setRuleType(bo.getRuleType());
        add.setRuleStatus(false);
        add.setTransferWork(bo.getTransferWork());
        add.setHandlerPerson(bo.getHandlerPerson());
        add.setSendMessage(bo.getSendMessage());

        return baseMapper.insert(add) > 0;

    }


    @Override
    public PageDataInfo selectPageList(DrainAlarmRuleReq request) {
        Page<DrainAlarmRuleVo> page = request.getPageQuery().build();
        Page<DrainAlarmRuleVo> result = drainAlarmRuleMapper.selectPageList(page, selectBuildQueryWrapper(request));
        // 处理字段映射
        handleFieldMapping(result.getRecords());
        processConditionsForList(result.getRecords());
        return PageDataInfo.build(result);
    }

    /**
     * 处理列表中所有项的条件转换和字典映射
     */
    private void processConditionsForList(List<DrainAlarmRuleVo> ruleVoList) {
        if (ruleVoList == null || ruleVoList.isEmpty()) {
            return;
        }

        // 获取字典数据(只查询一次，提高效率)
        List<DataDictionary> dataDictionaries = alarmRuleDictionary();
        if (dataDictionaries == null || dataDictionaries.isEmpty()) {
            return;
        }

        // 转换为Map便于查询
        Map<String, String> dictMap = dataDictionaries.stream()
                .collect(Collectors.toMap(
                        DataDictionary::getDictValue,
                        DataDictionary::getDictLabel,
                        (existing, replacement) -> existing
                ));

        // 处理每个项
        ruleVoList.forEach(ruleVo -> processConditions(ruleVo, dictMap));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertOrUpdateBo(DrainAlarmRuleBo bo) {
        // 1) 参数兜底
        if (bo == null || StringUtils.isBlank(bo.getAlarmType()) || StringUtils.isBlank(bo.getFacilityType())) {
            throw new BaseException("参数不完整：alarmType/facilityType 不能为空");
        }

        // 不让用户重复新增设施为全部=0的报警规则，如果数据库中有，则不允许新增。
        if ("0".equals(bo.getDeviceIds())) {
            LambdaQueryWrapper<DrainAlarmRule> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(DrainAlarmRule::getAlarmType, bo.getAlarmType())
                    .eq(DrainAlarmRule::getFacilityType, bo.getFacilityType())
                    .eq(DrainAlarmRule::getDeviceIds, "0")
                    .eq(DrainAlarmRule::getDeleted, 0);
            if (drainAlarmRuleMapper.selectCount(updateWrapper) > 0) {
                throw new BaseException("已存在相同设施类型的为全部的报警规则，请勿重复添加");
            }
        }

        // 2) 当选择“全部设备(0)”时，先清理同类型未删除的规则
        if ("0".equals(bo.getDeviceIds())) {
            LambdaQueryWrapper<DrainAlarmRule> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(DrainAlarmRule::getAlarmType, bo.getAlarmType())
                    .eq(DrainAlarmRule::getFacilityType, bo.getFacilityType())
                    .eq(DrainAlarmRule::getDeleted, 0);
            drainAlarmRuleMapper.delete(updateWrapper);
        }

        // 3) 解析设备ID集合（支持单个/多个）
        List<String> targetDeviceIds = new ArrayList<>();
        if (StringUtils.isNotBlank(bo.getDeviceIds()) && bo.getDeviceIds().contains(",")) {
            for (String deviceId : bo.getDeviceIds().split(",")) {
                if (StringUtils.isNotBlank(deviceId)) {
                    targetDeviceIds.add(deviceId.trim());
                }
            }
        } else if (StringUtils.isNotBlank(bo.getDeviceIds())) {
            targetDeviceIds.add(bo.getDeviceIds().trim());
        } else {
            // 未提供deviceIds时，按单条空设备处理（不建议出现）
            targetDeviceIds.add(bo.getDeviceIds());
        }

        boolean allOk = true;

        // 4) 针对每个设备ID：存在则更新，不存在则新增；如包含条件则对条件做按规则ID的插入/更新
        for (String deviceId : targetDeviceIds) {
            // 4.1 查询是否已存在该设备的规则
            LambdaQueryWrapper<DrainAlarmRule> ruleWrapper = new LambdaQueryWrapper<>();
            ruleWrapper.eq(DrainAlarmRule::getAlarmType, bo.getAlarmType())
                    .eq(DrainAlarmRule::getFacilityType, bo.getFacilityType())
                    .eq(DrainAlarmRule::getDeviceIds, deviceId)
                    .eq(DrainAlarmRule::getDeleted, 0);

            DrainAlarmRule existRule = baseMapper.selectOne(ruleWrapper);

            if (existRule == null) {
                // 4.2 不存在则新增规则
                DrainAlarmRule addRule = new DrainAlarmRule();
                addRule.setAlarmType(bo.getAlarmType());
                addRule.setFacilityType(bo.getFacilityType());
                addRule.setDeviceIds(deviceId);
                addRule.setReceiverIds(bo.getReceiverIds());
                addRule.setIntervalValue(bo.getIntervalValue());
                addRule.setIntervalUnit(bo.getIntervalUnit());
                addRule.setRuleType(bo.getRuleType());
                addRule.setRuleStatus(Boolean.FALSE);
                addRule.setTransferWork(bo.getTransferWork());
                addRule.setHandlerPerson(bo.getHandlerPerson());
                addRule.setSendMessage(bo.getSendMessage());
                allOk = allOk && baseMapper.insert(addRule) > 0;
                existRule = addRule;
            } else {
                // 4.3 已存在则更新规则的基础信息（不改设备/类型）
                DrainAlarmRule updateRule = new DrainAlarmRule();
                updateRule.setId(existRule.getId());
                updateRule.setReceiverIds(bo.getReceiverIds());
                updateRule.setIntervalValue(bo.getIntervalValue());
                updateRule.setIntervalUnit(bo.getIntervalUnit());
                updateRule.setRuleType(bo.getRuleType());
                updateRule.setTransferWork(bo.getTransferWork());
                updateRule.setHandlerPerson(bo.getHandlerPerson());
                updateRule.setSendMessage(bo.getSendMessage());
                if (bo.getRuleStatus() != null) {
                    updateRule.setRuleStatus(bo.getRuleStatus());
                }
                allOk = allOk && baseMapper.updateById(updateRule) > 0;
            }

            // 4.4 如果包含多个条件，则循环对条件做“按规则ID”插入或更新
            if (bo.getConditions() != null) {
                for (DrainAlarmConditionBo conditionBo : bo.getConditions()) {
                    // 按(ruleId + monitorItemName + itemConditionOrder)尝试匹配已存在的条件
                    LambdaQueryWrapper<DrainAlarmCondition> condWrapper = new LambdaQueryWrapper<>();
                    condWrapper.eq(DrainAlarmCondition::getRuleId, existRule.getId());
                    if (conditionBo.getMonitorItemName() != null) {
                        condWrapper.eq(DrainAlarmCondition::getMonitorItemName, conditionBo.getMonitorItemName());
                    }
                    if (conditionBo.getItemConditionOrder() != null) {
                        condWrapper.eq(DrainAlarmCondition::getItemConditionOrder, conditionBo.getItemConditionOrder());
                    }

                    DrainAlarmCondition existCond = drainAlarmConditionMapper.selectOne(condWrapper);

                    DrainAlarmCondition cond = new DrainAlarmCondition();
                    if (existCond != null) {
                        cond.setId(existCond.getId());
                    }
                    cond.setRuleId(existRule.getId());
                    //  [充满度报警页面]设置monitor_item_name监测项名称或id（如"氨氮""前池液位"，直接存储） 默认为字典类型为 9=管网充满度
                    if ("5".equals(bo.getAlarmType())) {
                        // 9=管网充满度
                        cond.setMonitorItemName("9");
                    } else {
                        // 除了alarm_type页面之外正常存储
                        cond.setMonitorItemName(conditionBo.getMonitorItemName());
                    }
                    cond.setOperator(OperatorEnum.toSymbol(conditionBo.getOperator()));
                    cond.setThreshold(conditionBo.getThreshold());
                    cond.setRelation(conditionBo.getRelation());
                    cond.setItemConditionOrder(conditionBo.getItemConditionOrder());
                    cond.setSort(conditionBo.getSort() != null ? conditionBo.getSort() : (short) sortCounter.getAndIncrement());
                    cond.setFullLevel(conditionBo.getFullLevel());
                    cond.setPipeDiameter(conditionBo.getPipeDiameter());

                    allOk = allOk && drainAlarmConditionMapper.insertOrUpdate(cond);
                }
            }
        }

        return allOk;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateRuleAndConditions(DrainAlarmRuleBo bo) {
        if (bo == null ||
                (StringUtils.isBlank(bo.getId()) && (bo.getIds() == null || bo.getIds().isEmpty())) ||
                StringUtils.isBlank(bo.getAlarmType()) ||
                StringUtils.isBlank(bo.getFacilityType())) {
            throw new BaseException("参数不完整：id/alarmType/facilityType 不能为空");
        }

        List<String> ruleIds = new ArrayList<>();
        if (bo.getIds() != null && !bo.getIds().isEmpty()) {
            ruleIds.addAll(bo.getIds());
        } else if (StringUtils.isNotBlank(bo.getId())) {
            ruleIds = Arrays.stream(bo.getId().split(","))
                    .filter(StringUtils::isNotBlank)
                    .map(String::trim)
                    .distinct()
                    .collect(Collectors.toList());
        }

        boolean allOk = true;

        for (String ruleId : ruleIds) {
            DrainAlarmRule existingRule = baseMapper.selectById(ruleId);
            if (existingRule == null || existingRule.getDeleted() != 0) {
                throw new BaseException("报警规则数据未找到或已被删除，ruleId=" + ruleId);
            }

            // 设备ID不再删除，只更新
            DrainAlarmRule updateRule = new DrainAlarmRule();
            updateRule.setId(ruleId);
            updateRule.setDeviceIds(bo.getDeviceIds());
            updateRule.setReceiverIds(bo.getReceiverIds());
            updateRule.setIntervalValue(bo.getIntervalValue());
            updateRule.setIntervalUnit(bo.getIntervalUnit());
            updateRule.setRuleType(bo.getRuleType());
            updateRule.setTransferWork(bo.getTransferWork());
            updateRule.setHandlerPerson(bo.getHandlerPerson());
            updateRule.setSendMessage(bo.getSendMessage());
            if (bo.getRuleStatus() != null) {
                updateRule.setRuleStatus(bo.getRuleStatus());
            }
            allOk = allOk && baseMapper.updateById(updateRule) > 0;

            // 处理条件：先删除已有条件，再新增新的条件
            LambdaQueryWrapper<DrainAlarmCondition> condWrapper = new LambdaQueryWrapper<>();
            condWrapper.eq(DrainAlarmCondition::getRuleId, ruleId);
            drainAlarmConditionMapper.delete(condWrapper);

            if (bo.getConditions() != null && !bo.getConditions().isEmpty()) {
                for (DrainAlarmConditionBo conditionBo : bo.getConditions()) {
                    DrainAlarmCondition newCond = new DrainAlarmCondition();
                    newCond.setRuleId(ruleId);
                    // [充满度报警页面]设置monitor_item_name监测项名称或id（如"氨氮""前池液位"，直接存储） 默认为字典类型为 9=管网充满度
                    if ("5".equals(bo.getAlarmType())) {
                        // 9=管网充满度
                        newCond.setMonitorItemName("9");
                    } else {
                        // 除了alarm_type页面之外正常存储
                        newCond.setMonitorItemName(conditionBo.getMonitorItemName());
                    }
                    newCond.setOperator(OperatorEnum.toSymbol(conditionBo.getOperator()));
                    newCond.setThreshold(conditionBo.getThreshold());
                    newCond.setRelation(conditionBo.getRelation());
                    newCond.setItemConditionOrder(conditionBo.getItemConditionOrder());
                    newCond.setSort(conditionBo.getSort() != null ? conditionBo.getSort() : (short) 0);
                    newCond.setFullLevel(conditionBo.getFullLevel());
                    newCond.setPipeDiameter(conditionBo.getPipeDiameter());

                    allOk = allOk && drainAlarmConditionMapper.insert(newCond) > 0;
                }
            }

        }

        return allOk;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(DrainAlarmRuleBo bo) {
        if (ObjectUtil.isEmpty(bo) || ObjectUtil.isEmpty(bo.getId())) {
            throw new BaseException("参数不能为空，ID必须存在");
        }

        // 先根据ID查询记录是否存在
        DrainAlarmRule existingRule = baseMapper.selectById(bo.getId());
        if (existingRule == null || existingRule.getDeleted() != 0) {
            throw new BaseException("报警规则数据未找到或已被删除");
        }

        // 执行更新操作
        DrainAlarmRule update = new DrainAlarmRule();
        BeanUtils.copyProperties(bo, update);
        int rows = baseMapper.updateById(update);

        if (rows <= 0) {
            throw new BaseException("更新报警规则失败");
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(List<String> ids, boolean valid) {
        // 1.删除前先把对应id的条件删除
        drainAlarmConditionMapper.delete(new LambdaQueryWrapper<DrainAlarmCondition>().in(DrainAlarmCondition::getRuleId, ids));
        boolean flag = baseMapper.deleteBatchIds(ids) > 0;
        return flag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean removeRuleConditionById(List<String> list, boolean b) {
        boolean flag = drainAlarmConditionMapper.delete(new LambdaQueryWrapper<DrainAlarmCondition>().in(DrainAlarmCondition::getId, list)) > 0;
        return flag;
    }

    @Override
    public List<DataDictionary> alarmRuleDictionary() {
        final String dictType = "alarm_rule_type";
        List<DataDictionary> list = baseMapper.alarmRuleDictionary(dictType);
        return list;
    }

    @Override
    public List<String> getMonitorItemName(DrainAlarmRuleReq types) {
        // 查询所有符合条件的报警规则
        LambdaQueryWrapper<DrainAlarmRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DrainAlarmRule::getAlarmType, types.getAlarmType());
        wrapper.eq(DrainAlarmRule::getDeleted, 0);

        List<DrainAlarmRule> drainAlarmRules = baseMapper.selectList(wrapper);

        Set<String> descSet = new HashSet<>();

        for (DrainAlarmRule rule : drainAlarmRules) {
            LambdaQueryWrapper<DrainAlarmCondition> conditionWrapper = new LambdaQueryWrapper<>();
            conditionWrapper.eq(DrainAlarmCondition::getRuleId, rule.getId());
            conditionWrapper.eq(DrainAlarmCondition::getDeleted, 0);
            // 注意：monitorItemNameDesc 不是实体字段，不能在这里用 LambdaQueryWrapper 过滤

            // 查询 VO 列表（包含 monitorItemNameDesc）
            List<DrainAlarmConditionVo> conditionVos = drainAlarmConditionMapper.selectVoList(conditionWrapper);

            // 需要在DrainAlarmConditionVo中做字段映射
            processConditionsForItem(conditionVos);

            for (DrainAlarmConditionVo vo : conditionVos) {
                String desc = vo.getMonitorItemName();
                if (desc != null && !desc.trim().isEmpty()) {
                    descSet.add(desc.trim());
                }
            }
        }

        return new ArrayList<>(descSet); // 转为 List 返回
    }

    /**
     * 处理DrainAlarmConditionVo列表的字典映射
     */
    private void processConditionsForItem(List<DrainAlarmConditionVo> conditionVos) {
        if (conditionVos == null || conditionVos.isEmpty()) {
            return;
        }

        // 获取字典数据(只查询一次，提高效率)
        List<DataDictionary> dataDictionaries = alarmRuleDictionary();
        if (dataDictionaries == null || dataDictionaries.isEmpty()) {
            return;
        }

        // 转换为Map便于查询
        Map<String, String> dictMap = dataDictionaries.stream()
                .collect(Collectors.toMap(
                        DataDictionary::getDictValue,
                        DataDictionary::getDictLabel,
                        (existing, replacement) -> existing
                ));

        // 处理每个Vo对象的字典映射
        conditionVos.forEach(vo -> {
            String originalName = vo.getMonitorItemName();
            // 使用字典映射替换原始值，如果没有匹配则保留原始值
            String mappedName = dictMap.getOrDefault(originalName, originalName);
            vo.setMonitorItemName(mappedName);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean alarmSwitchStatus(DrainAlarmRuleBo bo) {
        if (ObjectUtil.isEmpty(bo)) {
            throw new BaseException("报警开关状态参数不能为空");
        }

        DrainAlarmRule drainAlarmRule = baseMapper.selectById(bo.getId());
        if (ObjectUtil.isEmpty(drainAlarmRule)) {
            throw new BaseException("报警规则数据未找到");
        }
        drainAlarmRule.setRuleStatus(bo.getRuleStatus());

        return baseMapper.updateById(drainAlarmRule) > 0;
    }

    @Override
    public List<String> getExistFacilityType(DrainAlarmRuleReq request) {
        LambdaQueryWrapper<DrainAlarmRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(DrainAlarmRule::getDeviceIds)
                .eq(DrainAlarmRule::getDeleted, 0)
                .eq(DrainAlarmRule::getAlarmType, request.getAlarmType());
        List<String> list = baseMapper.selectList(wrapper)
                .stream()
                .map(DrainAlarmRule::getDeviceIds).toList();
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateIntervalValue(DrainAlarmRuleReq request) {
        // 1.根据id查询数据是否存在
        DrainAlarmRule drainAlarmRule = baseMapper.selectById(request.getId());
        if (ObjectUtil.isEmpty(drainAlarmRule)) {
            throw new BaseException("数据不存在！");
        }

        // 2.构建更新对象
        DrainAlarmRule update = new DrainAlarmRule();
        update.setId(request.getId());
        update.setIntervalValue(request.getIntervalValue());
        update.setIntervalUnit(request.getIntervalUnit());
        update.setUpdateTime(LocalDateTime.now());
        update.setUpdater(getUsername());

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 按照条件查询告警规则
     *
     * @param request
     * @return
     */
    @Override
    public List<DrainAlarmRuleVo> queryDrainAlarmRule(DrainAlarmRuleReq request) {
        LambdaQueryWrapper<DrainAlarmRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(request.getAlarmType()), DrainAlarmRule::getAlarmType, request.getAlarmType());
        wrapper.eq(StringUtils.isNotBlank(request.getFacilityType()), DrainAlarmRule::getFacilityType, request.getFacilityType());
        wrapper.eq(DrainAlarmRule::getRuleStatus, Boolean.TRUE);
        wrapper.eq(DrainAlarmRule::getDeleted, 0);

        List<DrainAlarmRuleVo> drainAlarmRules = baseMapper.selectVoList(wrapper);

        return drainAlarmRules;
    }

}
